import {
  serviceType
} from '@/utils/formassembly/servicetype.js'
import {
  queryStd_admunitList
} from '@/api/std/std_admunit.js'
import {
  queryDeliveryPersonnel
} from '@/api/accept/apl_arrive.js'
import {
  getPersonList
} from '@/api/correction/crc_person.js'
import { Decrypt } from '@/enumeration/SM.js'

export async function coreService(service, myValue, applyid) {
  console.log('自定义配置服务', service)
  switch (service) {
    // 查询行政管理单位列表
    case serviceType['admunitService'].value: {
      return await admunitService(myValue)
    }
    // 查询可送达人员列表
    case serviceType['arriveService'].value: {
      return await arriveService(myValue, applyid)
    }
    // 查询社矫对象信息列表
    case serviceType['correctionPerSonService'].value: {
      return await correctionPerSonService(myValue, applyid)
    }
    default: {
      console.error('未知的自定义服务', service)
    }
  }
}
// 查询社矫对象信息列表
async function correctionPerSonService(myValue) {
  let result = {
    data: null,
    value: []
  }
  const {
    data
  } = await getPersonList()
  result.data = data.map(v => {
    return {
      value: v.id,
      label: Decrypt(v.name)
    }
  })
  // 按中文排序
  result.data.sort((a, b) => {
    return a.label.localeCompare(b.label)
  })
  // 回显默认值
  if (myValue) {
    result.value = queryDefValue(result.data, myValue)
  }
  return result
}

// 查询行政管理单位列表
async function admunitService(myValue) {
  let result = {
    data: null,
    value: []
  }
  const {
    data
  } = await queryStd_admunitList()
  result.data = data.records.map(v => {
    return {
      value: v.id,
      label: v.name
    }
  })
  // 按中文排序
  result.data.sort((a, b) => {
    return a.label.localeCompare(b.label)
  })
  // 回显默认值
  if (myValue) {
    result.value = queryDefValue(result.data, myValue)
  }
  return result
}


// 查询可送达人员列表
async function arriveService(myValue, applyid) {
  let result = {
    data: null,
    value: []
  }
  const {
    data
  } = await queryDeliveryPersonnel(applyid)
  result.data = data
  // 回显默认值
  if (myValue) {
    result.value = queryDefValue(result.data, myValue)
  }
  return result
}

// 查询默认值
function queryDefValue(list, value) {
  let result = []
  let ids = value.split(',')
  list.forEach(v => {
    if (ids.includes(v.value)) {
      result.push(v.label)
    }
  })
  return result
}